import React, { Component } from 'react'
import {
    List,
    Avatar,
    Space,
    Image,
    Spin,
    Descriptions,
    Badge,
    Modal,
    message,
    Drawer,
    Form,
    Input,
    Button,
    Select
} from 'antd'
import { LikeOutlined, UserOutlined } from '@ant-design/icons'
import { requestCommentlist, requestReturnBack } from '../../api/comment'
import { requestShopDetail } from '../../api/shop'
import QueueAnim from 'rc-queue-anim'
import { connect } from 'react-redux'

const { TextArea } = Input
const { Option } = Select
const IconText = ({ icon, text }) => (
    <Space>
        {React.createElement(icon)}
        {text}
    </Space>
)

class Comment extends Component {
    state = {
        listHeight: window.innerHeight - 180,
        loading: true,
        shopDetail: {},
        shopDetailVisible: false,
        responseVisible: false,
        loadingDetail: true,
        username: '',
        commentid: '',
        formRef: React.createRef(),
        show: true,
        listData: []
    }

    componentDidMount () {
        this.init()
    }

    init () {
        requestCommentlist().then(res => {
            this.setState({
                listData: res.data,
                originData: res.data
            })
            setTimeout(() => {
                this.setState({
                    loading: false
                })
            }, 100)
        })
    }

    renderImgList (imgs) {
        let element = null
        if (!imgs.length) {
            return null
        }
        element = imgs.slice(0, 3).map(item => (<Image width={150} height={150} alt="" src={item} placeholder={
            <Image
                preview={false}
                src="https://web.chengqige.com/vipshop/v1/dist/static/loading.gif"
                width={150}
                height={150}
                mode="cover"
            />
        }/>))
        return element
    }

    getDetail (proid) {
        this.setState({
            shopDetailVisible: true
        })
        requestShopDetail(proid).then(res => {
            this.setState({
                loadingDetail: false,
                shopDetail: res.data,
            })
        })
        console.log(proid)
    }

    copyWhenClick (text, tip = '复制商品id成功！') {
        console.log(text, tip)
        const copyer = document.getElementById('copy')
        copyer.value = text
        copyer.select()
        document.execCommand('copy')
        message.success(tip)
    }

    onCancel () {
        this.setState({
            shopDetailVisible: false,
            loadingDetail: true
        })
    }

    onClose () {
        this.setState({
            responseVisible: false,
        })
        this.state.formRef.current.resetFields()
    }

    responce (commentid, username) {
        console.log(commentid)
        this.setState({
            responseVisible: true,
            username,
            commentid
        })
    }

    onFinish (values) {
        let { commentid } = this.state
        let { msg } = values
        requestReturnBack(commentid, msg).then(res => {
            console.log(res)
            this.init()
        })
    }

    handleChange (text) {
        let filters = () => {}
        switch (text) {
            case '全部评论':
                filters = (item => item)
                break
            case '好评':
                filters = (item => item.star > 3)
                break
            case '中评':
                filters = (item => item.star === 3)
                break
            case '差评':
                filters = (item => item.star < 3)
                break
            default :
                console.log('extra')
                break
        }
        const filter = this.state.originData.filter(filters)
        this.setState({
            listData:[...filter]
        })
    }

    element (listData) {
        let element = null
        if (this.state.loading) {
            element = (<div className="loading">
                <Spin tip="Loading..." spinning={this.state.loading} size="large"/>
            </div>)
        } else {
            element = (
                <>
                    <Select defaultValue="全部评论" style={{ width: 120, marginBottom: 20 }}
                            onChange={this.handleChange.bind(this)}>
                        <Option value="全部评论">全部评论</Option>
                        <Option value="好评">好评</Option>
                        <Option value="中评">中评</Option>
                        <Option value="差评">差评</Option>
                    </Select>
                    <List
                        itemLayout="vertical"
                        size="large"
                        style={{ height: this.state.listHeight, overflow: 'auto' }}
                        pagination={{
                            onChange: page => {
                                console.log(page)
                            },
                            pageSize: 3,
                        }}
                        rowKey={record => {
                            return record.commentid
                        }}
                        dataSource={listData}
                        renderItem={item => (
                            <>
                                <List.Item
                                    style={{ position: 'relative' }}
                                    actions={[
                                        <IconText icon={LikeOutlined}
                                                  text={item.star > 3 ? '好评' : item.star === 3 ? '中评' : '差评'}
                                                  key="list-vertical-star-o"/>,
                                        // eslint-disable-next-line
                                        <a style={{ color: '#00000078' }}
                                           onClick={this.responce.bind(this, item.commentid, item.username)}>回复</a>,
                                        <div>{item.msg ? '我的回复：' + item.msg : ''}</div>
                                    ]}
                                    extra={
                                        <Image.PreviewGroup>
                                            {this.renderImgList(item.imgs)}
                                        </Image.PreviewGroup>
                                    }
                                >
                                    <List.Item.Meta
                                        avatar={<Avatar size="large" icon={<UserOutlined/>}/>}
                                        // eslint-disable-next-line
                                        title={<a>{item.username}</a>}
                                        // eslint-disable-next-line
                                        description={<a onClick={this.getDetail.bind(this, item.proid)}>商品详情</a>}
                                    />
                                    {item.content}
                                </List.Item>
                            </>
                        )}
                    />
                    <Drawer title={'回复' + this.state.username} width={500} placement="right"
                            onClose={this.onClose.bind(this)}
                            visible={this.state.responseVisible}>
                        <Form
                            ref={this.state.formRef}
                            name="basic"
                            labelCol={{ span: 4 }}
                            initialValues={{ remember: true }}
                            onFinish={this.onFinish.bind(this)}
                            autoComplete="off"
                        >
                            <Form.Item
                                label="回复"
                                name="msg"
                                rules={[{ required: true, message: '请输入回复内容' }]}
                            >
                                <TextArea rows={4} placeholder="请输入回复内容"/>
                            </Form.Item>
                            <Form.Item wrapperCol={{ offset: 4, span: 16 }}>
                                <Button type="primary" htmlType="submit">
                                    提交
                                </Button>
                            </Form.Item>
                        </Form>
                    </Drawer>
                    <Modal width={1000} footer={null} visible={this.state.shopDetailVisible}
                           onCancel={this.onCancel.bind(this)}>
                        {this.state.loadingDetail ? (
                            <div className="loading" style={{ display: 'flex', justifyContent: 'center' }}>
                                <Spin tip="获取中..." spinning={this.state.loadingDetail} size="large"/>
                            </div>) : (<Descriptions title="商品详情" bordered>
                            {/*eslint-disable-next-line*/}
                            <Descriptions.Item label="商品名称"><a title="点击复制id"
                                                               onClick={this.copyWhenClick.bind(this, this.state.shopDetail.proid, '复制商品id成功')}>{this.state.shopDetail.proname}</a></Descriptions.Item>
                            <Descriptions.Item label="品牌">{this.state.shopDetail.brand}</Descriptions.Item>
                            <Descriptions.Item label="分类">{this.state.shopDetail.category}</Descriptions.Item>
                            <Descriptions.Item label="商品原价">{this.state.shopDetail.originprice}</Descriptions.Item>
                            <Descriptions.Item label="商品折扣" span={2}>
                                {this.state.shopDetail.discount}
                            </Descriptions.Item>
                            <Descriptions.Item label="商品状态" span={1}>
                                <Badge status="processing" text={this.state.shopDetail.issale ? '上架中' : '已下架'}/>
                            </Descriptions.Item>
                            <Descriptions.Item label="商品库存" span={2}>{this.state.shopDetail.stock}</Descriptions.Item>
                            <Descriptions.Item label="上架时间" span={1}>{this.state.shopDetail.time}</Descriptions.Item>
                            <Descriptions.Item label="商品销量" span={2}>{this.state.shopDetail.sales}</Descriptions.Item>
                        </Descriptions>)}
                    </Modal>
                </>
            )
        }
        return element
    }

    render () {
        return (<QueueAnim className="demo-content" key="demo">
            {this.props.show ? <div className="demo-tbody" key="a">{this.element(this.state.listData)}</div> : null}
        </QueueAnim>)
    }
}

export default connect((state) => {
    return {
        show: state.getIn(['fade', 'show'])
    }
})(Comment)
